package com.acme.bankapp.service.bank;

import java.io.*;

import com.acme.bankapp.domain.bank.*;
import com.acme.bankapp.exceptions.*;

/**
 * This class implements some service functionality
 * 
 * @author Anton Kotov
 * 
 */
public class BankService {
    public static Bank addClients(final Bank bank, final Client... clients)
	    throws ClientExistsException {
	Bank ret = bank;
	for (Client client : clients) {
	    ret = addClient(ret, client);
	}
	return ret;
    }

    public static Bank addClient(final Bank bank, final Client client)
	    throws ClientExistsException {
	return bank.addClient(client);
    }

    public static Client addAccounts(final Client client,
	    final Account... accounts) {
	Client ret = client;
	for (Account account : accounts) {
	    ret = addAccount(ret, account);
	}
	return ret;
    }

    public static Client addAccount(final Client client, final Account account) {
	return client.addAccount(account);
    }

    public static void modifyBank(final Bank bank)
	    throws NotEnoughFundsException {
	for (Client client : bank.getClients()) {
	    for (Account account : client.getAccounts()) {
		account.deposit(2 * Math.random());
		account.withdraw(3 * Math.random());
	    }
	}
    }

    public static void printBalance(final Bank bank) {
	System.out.println("--balance--");
	for (Client client : bank.getClients()) {
	    System.out.println(client);
	}
    }

    public static void printMaximumAmountToWithdraw(final Bank bank) {
	System.out.println("--maximum amount to withdraw--");
	for (Client client : bank.getClients()) {
	    for (Account account : client.getAccounts()) {
		System.out.println(client + "; maximum amount to withdraw : "
			+ account.maximumAmountToWithdraw());
	    }
	}
    }

    public static void saveBank(final String fileName, final Bank bank)
	    throws FileNotFoundException, IOException {
	try (ObjectOutputStream oos = new ObjectOutputStream(
		new FileOutputStream(fileName))) {
	    oos.writeObject(bank);
	}
    }

    public static Bank loadBank(final String fileName)
	    throws ClassNotFoundException, IOException {
	Object object = null;
	try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
		fileName))) {
	    object = ois.readObject();
	}
	if (object instanceof Bank) {
	    return (Bank) object;
	} else {
	    return null;
	}
    }
}
